/*
 * Copyright (C) 2012 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.huika.dealontop.control.nearby.activity;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.location.Location;
import android.location.LocationListener;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnMyLocationButtonClickListener;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.PolylineOptions;
import com.huika.dealontop.R;
import com.huika.dealontop.control.base.BaseAct;
import com.huika.dealontop.utils.GMapUtil;
import com.huika.dealontop.utils.PermissionUtils;
import com.huika.dealontop.views.TitleBarHelper;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * @author chenyuan
 * @description：google 地图，路线规划（包括定位）http://maps.google.com/maps/api/geocode/json?latlng=22.604852,114.053761&sensor=true
 * @date 2015年11月16日 上午11:25:04
 */
public class GMapActivity extends BaseAct
        implements
        OnMyLocationButtonClickListener,
        OnMapReadyCallback,
        ActivityCompat.OnRequestPermissionsResultCallback, LocationListener {

    private static final int LOCATION_PERMISSION_REQUEST_CODE = 1;
    public static final String MERCHANTNAME = "merchant_name";
    public static final String MERCHANTADDRESS = "merchant_adress";
    public static final String MERCHANTLAT = "merchant_lat";
    public static final String MERCHANTLNG = "merchant_lng";
    private boolean mPermissionDenied = false;
    private GoogleMap mMap;
    private TextView shop_name_tv;
    private TextView geo_location_tv;
    private Location location;
    private GMapUtil gMapUtil ;
    private RelativeLayout walking_Loy;
    private RelativeLayout travling_Loy;
    private RelativeLayout navigation_loy;
    private LatLng origin;//origin=22.604852,114.053761
    private LatLng destination;//测试22.704737, 114.023556
//    private LatLng destination=new LatLng(22.704737, 114.023556);//测试22.704737, 114.023556

    private String goWay;
    private int color;
    private int lineWith=13;
    private String merchantName;
    private String merchantAddress;
    private Double merchantLat;
    private Double merchantLng;

    @Override
    protected void initData() {
        super.initData();
        //初始化商家位置信息
        merchantName = getIntent().getStringExtra(MERCHANTNAME);
        merchantAddress = getIntent().getStringExtra(MERCHANTADDRESS);
        merchantLat = getIntent().getDoubleExtra(MERCHANTLAT,0);
        merchantLng = getIntent().getDoubleExtra(MERCHANTLNG, 0);
        destination = new LatLng(merchantLat,merchantLng);

        Log.d("cy", "merchantName: merchantAddress:merchantLat:merchantLng:destination" + merchantName + merchantAddress + merchantLat + merchantLng + destination);
    }

    @Override
    public void setRootView() {
        setContentView(R.layout.activity_gmap);
    }

    @Override
    protected void initWidget() {
        super.initWidget();
        gMapUtil = new GMapUtil(this);
        new TitleBarHelper(this, R.string.common_empty, R.string.common_empty, R.string.shop_detail_title).setRightPop();
        SupportMapFragment mapFragment =
                (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);
        walking_Loy = (RelativeLayout) findViewById(R.id.walking_Loy);
        navigation_loy = (RelativeLayout) findViewById(R.id.navigation_loy);
        travling_Loy = (RelativeLayout) findViewById(R.id.travling_Loy);
        shop_name_tv = (TextView) findViewById(R.id.shop_name_tv);
        navigation_loy.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                    if (gMapUtil.checkGoogleMap()){

                        Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(String.format("http://ditu.google.cn/maps?hl=zh&mrt=loc&q=%s,%s",merchantLat,merchantLng)));
                        i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK & Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
                        i.setClassName("com.google.android.apps.maps", "com.google.android.maps.MapsActivity");
                        startActivity(i);
                    }else{
                        showToastMsg(getString(R.string.shop_detail_not_install_map));
                    }

            }
        });
        geo_location_tv = (TextView) findViewById(R.id.geo_location_tv);
        geo_location_tv.setText(merchantAddress);
        shop_name_tv.setText(merchantName);
        walking_Loy.setOnClickListener(this);
        travling_Loy.setOnClickListener(this);
    }

    @Override
    public void widgetClick(View v) {
        super.widgetClick(v);
        switch (v.getId()) {
            case R.id.walking_Loy:
                /**测试地图路线规划*/
                goWay = "walking";
                color = Color.RED;
                if (origin!=null&&destination!=null)
                drawLine(origin, destination, goWay);//origin=22.604852,114.053761
                break;
            case R.id.travling_Loy:
                /**测试地图路线规划*/
                goWay = "driving";
                color = Color.GREEN;
                if (origin!=null&&destination!=null)
                drawLine(origin, destination, goWay);
                break;
        }
    }


    @Override
    public void onMapReady(GoogleMap map) {
        mMap = map;

        //设置定位的图标可见
        mMap.setOnMyLocationButtonClickListener(this);
        enableMyLocation();

        if (mMap != null) {
            /**添加终点标记*/
            drawOriginMarker(destination, getString(R.string.shop_detail_destination), 1);
        }
        handler.sendEmptyMessageDelayed(0, 3000);

    }

    private android.os.Handler handler = new android.os.Handler() {
        @Override
        public void handleMessage(Message msg) {
            onMyLocationButtonClick();
        }
    };

    private void drawLine(LatLng origin, LatLng destination, String goWay) {
        //创建线程运行请求数据，并画线
        new DownloadTask().execute(gMapUtil.getDirectionsUrl(origin, destination, goWay));
        Log.d("cy", "请求路径为：" + gMapUtil.getDirectionsUrl(origin, destination, goWay) + "");
    }


    /**
     * 显示我的位置标记到地图中，保证已经定义好了权限
     */
    private void enableMyLocation() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED) {
            PermissionUtils.requestPermission((AppCompatActivity) aty, LOCATION_PERMISSION_REQUEST_CODE,
                    Manifest.permission.ACCESS_FINE_LOCATION, true);
        } else if (mMap != null) {
            mMap.setMyLocationEnabled(true);//显示我的位置到地图中
        }
    }

    @Override
    public boolean onMyLocationButtonClick() {
        if (mMap != null) {
            if (mMap.getMyLocation() != null) {
                Log.d("cy", mMap.getMyLocation() + "click");
                origin = new LatLng(mMap.getMyLocation().getLatitude(), mMap.getMyLocation().getLongitude());
                mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(origin,
                        16));
            }
        }

        return false;
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        if (requestCode != LOCATION_PERMISSION_REQUEST_CODE) {
            return;
        }

        if (PermissionUtils.isPermissionGranted(permissions, grantResults,
                Manifest.permission.ACCESS_FINE_LOCATION)) {
            enableMyLocation();
        } else {
            mPermissionDenied = true;
        }
    }

    @Override
    protected void onResumeFragments() {
        super.onResumeFragments();
        if (mPermissionDenied) {
            showMissingPermissionError();
            mPermissionDenied = false;
        }
    }

    /**
     * 位置权限丢失对话框
     */
    private void showMissingPermissionError() {
        PermissionUtils.PermissionDeniedDialog
                .newInstance(true).show(getSupportFragmentManager(), "dialog");
    }

    /**
     * 划起点的标记
     */
    private void drawOriginMarker(LatLng latLng, String title, int flag) {
//        mMap.clear();

        //添加标记
        MarkerOptions markerOptions = new MarkerOptions();

        markerOptions.position(latLng);
        markerOptions.visible(true);
        markerOptions.anchor(0.5f, 0.5f);
        markerOptions.draggable(false);
        if (flag == 1) {
            markerOptions.icon(BitmapDescriptorFactory
                    .fromResource(R.mipmap.shop_address_marker_icon));
        } else {
        }

        markerOptions.title(title);
        mMap.addMarker(markerOptions);
    }

    @Override
    public void onLocationChanged(Location location) {
        if (mMap != null) {
            Log.d("cy", location.getLatitude() + " " + location.getLongitude() + " locationChanged");
        }
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {

    }

    @Override
    public void onProviderEnabled(String provider) {

    }

    @Override
    public void onProviderDisabled(String provider) {

    }


    // Fetches data from url passed,使用异步操作AsynTask实现downurl json 数据
    public class DownloadTask extends AsyncTask<String, Void, String> {

        // Downloading data in non-ui thread
        @Override
        protected String doInBackground(String... url) {

            // For storing data from web service
            String data = "";

            try {
                // Fetching the data from web service
                data = gMapUtil.downloadUrl(url[0]);
                Log.d("cy", "url[0]为：" + url[0] + "");
                Log.d("cy", "DownloadTask data为：" + data + "");
            } catch (Exception e) {
                Log.d("Background Task", e.toString());
            }
            return data;
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);

            ParserTask parserTask = new ParserTask(mMap);

            Log.d("cy", "DownloadTask result为：" + result + "" + result.length());
            // Invokes the thread for parsing the JSON data
            parserTask.execute(result);

        }
    }


    /**
     * A class to parse the Google Places in JSON format
     * 异步操作，转换得到的 Google Place json数据，然后显示在google map上。
     */
    public class ParserTask extends
            AsyncTask<String, Integer, List<List<HashMap<String, String>>>> {
        private GoogleMap mGoogleMap;

        public ParserTask() {
        }

        public ParserTask(GoogleMap map) {
            mGoogleMap = map;
        }

        @Override
        protected List<List<HashMap<String, String>>> doInBackground(
                String... jsonData) {

            JSONObject jObject;
            List<List<HashMap<String, String>>> routes = null;

            try {
                jObject = new JSONObject(jsonData[0]);
                Log.d("cy", "ParserTask jsonData[0]为：" + jsonData[0] + "");

                // Starts parsing data
                routes = gMapUtil.parse(jObject);
                System.out.println("do in background:" + routes);
                Log.d("cy", "ParserTask routes为：" + routes + "");
            } catch (Exception e) {
                e.printStackTrace();
            }
            return routes;
        }

        @Override
        protected void onPostExecute(List<List<HashMap<String, String>>> result) {

            Log.d("cy", "ParserTask result为：" + result + "");
            ArrayList<LatLng> points = null;
            PolylineOptions lineOptions = null;
            MarkerOptions markerOptions = new MarkerOptions();

            if (!result.isEmpty()) {


                // Traversing through all the routes
                for (int i = 0; i < result.size(); i++) {
                    points = new ArrayList<LatLng>();
                    lineOptions = new PolylineOptions();

                    List<HashMap<String, String>> path = result.get(i);

                    for (int j = 0; j < path.size(); j++) {
                        HashMap<String, String> point = path.get(j);

                        double lat = Double.parseDouble(point.get("lat"));
                        double lng = Double.parseDouble(point.get("lng"));
                        LatLng position = new LatLng(lat, lng);

                        points.add(position);
                    }

                    Log.d("cy", "ParserTask points为：" + points + "共" + points.size() + "个点");
                    lineOptions.addAll(points);
                    lineOptions.width(lineWith);

                    lineOptions.color(color);
                }
            } else {
                showToastMsg(getString(R.string.shop_detail_destination_des));
            }
            Log.d("cy", "ParserTask lineOptions为：" + lineOptions + "");
            if (lineOptions != null)
                mGoogleMap.addPolyline(lineOptions);
        }
    }

}
